<?php
/**
 * Created by PhpStorm.
 * User: lingyun
 * Date: 2018/3/26
 * Time: 16:12
 * Desc: 原料管理
 */
namespace app\kuguan\controller;
use controller\BasicAdmin;
use service\DataService;
use think\Db;
use app\mall\model\GoodsStockLog;
use app\mall\model\StoreOrderGoods;
use app\mall\model\GoodsSpecDetail;
use app\kuguan\model\StoreGoodsStockModel;
class Apply extends BasicAdmin{

    /**
     * @Author      Hybrid
     * @DateTime    2018-05-04
     * @Description 店内购货申请订单
     * @return      [type]     [description]
     */
    public function diannei_order(){
        $this->title = '店内商品购货申请';
        $get = $this->request->get();
        $map = array();
        $map['a.status'] = array('neq',4);
        $map['a.type'] = array('in','0,1');
        $map['a.is_deleted'] = array('eq',0);
        $map['a.is_diannei'] = array('eq',1);
        if(!empty($get['sn'])){
            $this->assign('sn',$get['sn']);
            $map['a.sn'] = array('like','%'.$get['sn'].'%');
        }else{
            $this->assign('sn',0);
        }
        $rows = intval($this->request->get('rows', cookie('rows')));
        cookie('rows', $rows >= 10 ? $rows : 20);
        $page = Db::name('store_order')->alias('a')->join('store b','a.store_id=b.id','LEFT')->where($map)->field('a.*,b.title')->order('a.id desc')->paginate($rows, false, ['query' => request()->get('', '', 'urlencode')]);
        list($pattern, $replacement) = [['|href="(.*?)"|', '|pagination|'], ['data-open="$1"', 'pagination pull-right']];
        list($result['list'], $result['page']) = [$page->all(), preg_replace($pattern, $replacement, $page->render())]; 
        $this->assign('title',$this->title);            //必须加上title,不然顶部的按钮不会显示
        return $this->fetch('diannei_order', $result);
    }

    /**
     * @Author      Hybrid
     * @DateTime    2018-05-04
     * @Description 商品购货申请
     * @return      [type]     [description]
     */
    public function order(){
        $this->title = '商品购货申请';
        $get = $this->request->get();
        $map = array();
        $map['a.status'] = array('neq',4);
        $map['a.type'] = array('in','0,1');
        $map['a.is_deleted'] = array('eq',0);
        $map['a.is_diannei'] = array('eq',0);
        if(!empty($get['sn'])){
            $this->assign('sn',$get['sn']);
            $map['a.sn'] = array('like','%'.$get['sn'].'%');
        }else{
            $this->assign('sn',0);
        }
        $rows = intval($this->request->get('rows', cookie('rows')));
        cookie('rows', $rows >= 10 ? $rows : 20);
        $page = Db::name('store_order')->alias('a')->join('store b','a.store_id=b.id','LEFT')->where($map)->field('a.*,b.title')->order('a.id desc')->paginate($rows, false, ['query' => request()->get('', '', 'urlencode')]);
        list($pattern, $replacement) = [['|href="(.*?)"|', '|pagination|'], ['data-open="$1"', 'pagination pull-right']];
        list($result['list'], $result['page']) = [$page->all(), preg_replace($pattern, $replacement, $page->render())]; 
        $this->assign('title',$this->title);            //必须加上title,不然顶部的按钮不会显示
        return $this->fetch('order', $result);
    }
        
    /**
     * @Author      Hybrid
     * @DateTime    2018-05-04
     * @Description 订单详情
     * @return      [type]     [description]
     */
    public function order_detail(){
        $this->title = '订单详情';
        $id = input('id'); 
        $get = $this->request->get();
        $map = array();
        $map['a.is_deleted'] = array('eq',0);
        $map['a.order_id'] = array('eq',$id);
        $rows = intval($this->request->get('rows', cookie('rows')));
        cookie('rows', $rows >= 10 ? $rows : 20);
        $rows = 10000;
        $status = Db::name('store_order')->where('id',$id)->value('status');
        $page = Db::name('store_order_goods')->alias('a')->join('ys_goods b','a.goods_id=b.id','LEFT')->join('ys_goods_spec_detail c','a.goods_spec_id=c.id','LEFT')->where($map)->field('a.*,b.name,b.unit,c.title')->paginate($rows, false, ['query' => request()->get('', '', 'urlencode')]);
        list($pattern, $replacement) = [['|href="(.*?)"|', '|pagination|'], ['data-open="$1"', 'pagination pull-right']];
        list($result['list'], $result['page']) = [$page->all(), preg_replace($pattern, $replacement, $page->render())];

        $order = db('store_order')->where('id',input('id'))->find();

        $this->assign('title',$this->title);            //必须加上title,不然顶部的按钮不会显示
        $this->assign('id',$id);
        $this->assign('status',$status);
        $this->assign('order',$order);
        return $this->fetch('order_detail', $result);
    }

    /**
     * @Author      Hybrid
     * @DateTime    2018-05-04
     * @Description 发货
     * @return      [type]     [description]
     */
    public function deal_send(){
        if(request()->isPost()){
            $data = input('post.');
            $result = $this->StoreOrderGoodsData($data);        //构造数据

            if($result['code'] == 1){
                $model1 = new StoreOrderGoods();
                $model2 = new GoodsStockLog();
                $model3 = new GoodsSpecDetail();
                $model4 = new StoreGoodsStockModel();

                $model1->saveall($result['data']['data1']);
                $model2->saveall($result['data']['data2']);
                $model3->saveall($result['data']['data3']);
                $model4->saveall($result['data']['data6']);
                $res = Db::name('store_order')->where('id',$data['orderid'])->update(['deal_time'=>time(),'status'=>1,'deal_admin'=>session('user.id'),'sale_price'=>$result['data']['data4'],'chengben'=>$result['data']['data5']]);
                $res!==false?$this->success('处理成功',''):$this->error('处理失败','');
            }else{
                $this->error($result['msg'],'');
            }
        }else{
            $orderid = input('id');         //订单id
            $list = Db::name('store_order_goods')->alias('a')->join('ys_goods b','a.goods_id=b.id','LEFT')->join('ys_goods_spec_detail c','a.goods_spec_id=c.id','LEFT')->where('a.order_id',$orderid)->field('a.*,b.name,b.unit,c.stock,c.title,c.specs')->select();       //查询订单详情
//             halt($list);
            $this->assign('list',$list);
            $this->assign('orderid',$orderid);
            $this->assign('title','发货处理');
            return $this->fetch('deal_send');
        }
    }

    /**
     * @Author      Hybrid
     * @DateTime    2018-05-04
     * @Description 驳回发货申请
     * @return      [type]     [description]
     */
    public function deal_rebat(){
        $orderid = input('id');
        if(request()->isPost()){
            $da = input('post.');
                $res = Db::name('store_order')->where('id',$orderid)->update(['deal_time'=>time(),'status'=>2,'remark'=>$da['remark'],'deal_admin'=>session('user.id')]);
                $res!==false?$this->success('已驳回',''):$this->error('驳回失败','');
        }else{
            $this->assign('orderid',$orderid);
            return $this->fetch('deal_rebat');
        }
    }

    /**
     * @Author      Hybrid
     * @DateTime    2018-05-04
     * @Description 购货申请入库数据
     * @param       [type]     $post [description]
     */
    private function StoreOrderGoodsData($post){
        $sale_price = 0;            //工厂售卖总价
        $signal_chegnben = 0;            //工厂成本
        $order = db('store_order')->where('id',$post['orderid'])->find();              //订单信息

        $store = db('store')->where('id',$order['store_id'])->find();
        foreach($post['stock'] as $k => $v){
            if($order['is_diannei'] != 1){
                if($v < $post['del_num'][$k]){
                    return ['code'=>0,'msg'=>$post['goods_name'][$k].'库存不足','data'=>array()];
                    break;
                } 
            }
            $store_goods_stock = db('store_goods_stock')->where(['goods_id'=>$post['goods_id'][$k],'store_id'=>$order['store_id'],'goods_spec_id'=>$post['goods_spec_id'][$k]])->find();

            $peifang_ids = db('goods_spec_detail')->where('id',$post['goods_spec_id'][$k])->value('peifang_ids');
            if(!empty($peifang_ids)){
                $sql = "select sum(chengben_price) as signal_chengben ,sum(chengben) as s_chengben from ys_goods_peifang where id in (".$peifang_ids.")";
                $res = Db::query($sql);
                $signal_chengben = $res[0]['signal_chengben'];
                $chengben = $post['del_num'][$k]*$signal_chengben;
                $s_s_chengben = $res[0]['s_chengben'];
                $s_chengben = $post['del_num'][$k]*$s_s_chengben;
            }else{
                $signal_chengben = 0;
                $chengben = 0;
                $s_s_chengben = 0;
                $s_chengben = 0;
            }

            $sale_price +=$chengben;            //工厂售卖价
            $signal_chegnben += $s_chengben;
                  
            $res1[$k]['id'] = $post['id'][$k];      //主键id
            $res1[$k]['del_num'] = $post['del_num'][$k];
            $res1[$k]['deal_time'] = time();        
            $res1[$k]['sale_signal_price'] = $signal_chengben;
            $res1[$k]['sale_price'] = $chengben;
            $res1[$k]['signal_chengben'] = $s_s_chengben;
            $res1[$k]['chengben'] = $s_chengben;

            $res6[$k]['goods_id'] = $post['goods_id'][$k];
            $res6[$k]['goods_spec_id'] = $post['goods_spec_id'][$k];
            $res6[$k]['specs'] = $post['specs'][$k];
            $res6[$k]['store_id'] = $post['store_id'][$k];
            if($store['is_jiameng'] == 1){          //加盟店
//                $res6[$k]['chengben'] = $signal_chengben;     //2018-09-13
                //2018-09-13  start
                $res6[$k]['chengben'] = $signal_chengben;          //直营店成本 -- 低
                $res6[$k]['chengben'] = ($store_goods_stock['stock']*$store_goods_stock['chengben']+$post['del_num'][$k]*$signal_chengben)/($store_goods_stock['stock']+$post['del_num'][$k]);       //加盟店成本 -- 高
                $res6[$k]['chengben'] = substr(sprintf("%.5f",$res6[$k]['chengben']),0,-1);
                //2018-09-13  end
            }else{
//                $res6[$k]['chengben'] = $s_s_chengben;        //2018-09-13

                //2018-09-13    start
                $res6[$k]['chengben'] = ($store_goods_stock['stock']*$store_goods_stock['chengben']+$post['del_num'][$k]*$s_s_chengben)/($store_goods_stock['stock']+$post['del_num'][$k]);          //直营店成本 -- 低
                $res6[$k]['chengben'] = substr(sprintf("%.5f",$res6[$k]['chengben']),0,-1);
                //2018-09-13    end

            }
            $res6[$k]['id'] = $store_goods_stock['id'];
            $res6[$k]['chengben_price'] = $signal_chengben;


            $res2[$k]['goods_id'] = $post['goods_id'][$k];
            $res2[$k]['goods_spec_id'] = $post['goods_spec_id'][$k];
            $res2[$k]['store_id'] = $post['store_id'][$k];
            $res2[$k]['sign'] = 2;      //门店发货
            $res2[$k]['type'] = 2;      //减少
            $res2[$k]['del_num'] = $post['del_num'][$k];        //发货数量
            $res2[$k]['rec_num'] = $post['del_num'][$k];        //实际发货数量
            $res2[$k]['dif_num'] = 0;       //差异数
            $res2[$k]['cur_num'] = $post['stock'][$k]-$post['del_num'][$k];     //当前库存
            $res2[$k]['remark'] = '';
            $res2[$k]['addtime'] = time();
            $res3[$k]['id'] = $post['goods_spec_id'][$k];       //商品属性详情id
            $res3[$k]['stock'] = $post['stock'][$k]-$post['del_num'][$k];
        }
        return ['code'=>1,'msg'=>'','data'=>array('data1'=>$res1,'data2'=>$res2,'data3'=>$res3,'data4'=>$sale_price,'data5'=>$signal_chegnben,'data6'=>$res6)];       //返回给更新的数据
    }

    /**
     * @Author  lingyun
     * @Desc    同意购货申请
     * 2018-06-04
     */
    public function agree_order(){
        $id = input('id');
        $flag = db('store_order')->where('id',$id)->update(['status'=>1,'deal_time'=>time()]);
        db('store_order_goods')->where('order_id',$id)->update(['status'=>1,'deal_time'=>time()]);
        $flag!==false?$this->success('处理成功',''):$this->error('处理失败','');
    }



}